package cz.gelion.shylock.invoice.web.subj

import org.apache.wicket.markup.html.panel.Panel
import org.apache.wicket.model.IModel
import cz.gelion.shylock.invoice.entity.SubjectUnit
import cz.gelion.shylock.invoice.Log
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.model.CompoundPropertyModel
import org.apache.wicket.markup.html.form.TextField
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink
import org.apache.wicket.ajax.AjaxRequestTarget
import org.apache.wicket.markup.html.form.TextArea
import cz.gelion.shylock.invoice.web.Application
import cz.gelion.shylock.invoice.web.comp.TaForm
import org.apache.wicket.markup.html.form.CheckBoxMultipleChoice
import cz.gelion.shylock.invoice.entity.Account
import org.apache.wicket.model.Model
import org.apache.wicket.markup.html.form.IChoiceRenderer
import org.apache.wicket.model.LoadableDetachableModel
import scala.language.implicitConversions
import scala.collection.convert.WrapAsScala.enumerationAsScalaIterator
import scala.collection.JavaConversions._
import cz.gelion.shylock.invoice.entity.SubjectUnitAccount
import org.apache.wicket.util.string.AppendingStringBuffer
import org.apache.wicket.util.value.IValueMap
import org.apache.wicket.util.value.ValueMap

class SubjectUnitEditorPanel(id:String, model:IModel[SubjectUnit]) extends Panel(id,model) with Log {
  
  log.trace("this(" + id + "," + model + ")")
  
  
  val form = new TaForm[SubjectUnit]("form", new CompoundPropertyModel(model))
  form.setOutputMarkupId(true)
  add(form)
  
  form.add(new TextField("name"))
  form.add(new TextArea("note"))
 
  var unitAccounts = new LoadableDetachableModel[java.util.List[SubjectUnitAccount]] {
    def load:java.util.List[SubjectUnitAccount] =  {
      	log.trace("unitAccounts.load()")
          val l = new java.util.ArrayList[SubjectUnitAccount]
          Application.em.createQuery("select a from Account a  where a.subject = :subj and a.id not in (select n.id.account.id from SubjectUnitAccount n where n.id.subjectUnit=:su)", classOf[Account])
          	.setParameter("subj", model.getObject.getSubject).setParameter("su", model.getObject).getResultList.foreach(acc => {
            log.trace("creating unit account")
            l.add(new SubjectUnitAccount(acc,model.getObject()))
          })
		  l.addAll(Application.em.createQuery("select a from SubjectUnitAccount a where a.id.subjectUnit=:s", classOf[SubjectUnitAccount])
      	    .setParameter("s", model.getObject).getResultList)
      	  l
    }
  }
  form.add(new CheckBoxMultipleChoice("accounts",
      new IModel[java.util.Collection[SubjectUnitAccount]] {
      	override def getObject:java.util.Collection[SubjectUnitAccount] = {
      	  log.trace("getting objects...");
      	  Application.em.createQuery("select a from SubjectUnitAccount a where a.id.subjectUnit=:s", classOf[SubjectUnitAccount])
      	    .setParameter("s", model.getObject()).getResultList
      	}  
      	override def setObject(a:java.util.Collection[SubjectUnitAccount]) = {
      	  log.trace("setting accounts: " + a)
      	  a.foreach(Application.em.persist(_))
      	  model.getObject.getAccounts.foreach(acc => {
      	    if (! a.contains(acc)) {
      	      log.trace("removing: " + acc)
      	      model.getObject.getAccounts.remove(acc)
      	      Application.em.remove(acc)
      	    }
      	  })
      	}
    	override def detach = {}
      }, unitAccounts,
      new IChoiceRenderer[SubjectUnitAccount] {
    	override def getDisplayValue(a:SubjectUnitAccount):Object = if (a.getId.getAccount.getNote == null)  a.getId.getAccount.getAccountNo else a.getId.getAccount.getNote 
    	override def getIdValue(a:SubjectUnitAccount,i:Int):String = a.getId.getAccount.getId + "-" + a.getId.getSubjectUnit.getId
      }
   ) {
    override def getAdditionalAttributes(index:Int, choice:SubjectUnitAccount):IValueMap = {
      return new ValueMap("title", choice.getId.getAccount.getAccountNo)
    }
  })
  
  
  form.add(new AjaxSubmitLink("link.ok") {
	 override def onSubmit(target:AjaxRequestTarget, form:Form[_]) {
	   log.trace("AjaxSubmitLink[link.ok].onSubmit")
	   //TODO
	 } 
	  override def onError(target:AjaxRequestTarget, form:Form[_]) {
	   log.trace("AjaxSubmitLink[link.ok].onError")
	   //TODO
	 } 
  });
  
}